package databaseVersionControl.infra.connection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import databaseVersionControl.infra.exception.DVCConnectionInfoEmptyException;
import databaseVersionControl.infra.exception.DVCGeneralException;

class ConnectionFactory {

	private static Connection connection;
	private static ConnectionInfo connectionInfo;

	private ConnectionFactory() {}

	static Connection getConnection() {
		if (connection == null) initializeConnection();
		return connection;
	}

	static void setConnectionInfo(ConnectionInfo info) {
		connectionInfo = info;
	}

	private static void validateConnectionInfo() {
		if (connectionInfo == null) throw new DVCConnectionInfoEmptyException("ConnectionInfo is Empty");
	}

	private static void loadConnection() throws ClassNotFoundException, SQLException {
		validateConnectionInfo();

		Class.forName(connectionInfo.getDriverClassName());

		connection = DriverManager.getConnection(connectionInfo.getUrl(), connectionInfo.getUserName(), connectionInfo
				.getPassword());
	}

	private static void initializeConnection() {
		try {
			loadConnection();
		} catch (SQLException e) {
			throw new DVCGeneralException("SQL Exception", e);
		} catch (ClassNotFoundException e) {
			throw new DVCGeneralException("JDBC Driver Not Found: " + connectionInfo.getDriverClassName(), e);
		}
	}

	static void reset() {
		connection = null;
	}

}